package com.UBC417.termproject.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.UBC417.termproject.Data.*;


@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet{
	private static final Logger log = Logger.getLogger(SubscribeServlet.class.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		// Get parameters		
		String userID = req.getParameter("emailSignin");
		String password = req.getParameter("passwordSignin");
		
		String forwardTo = "/account.jsp";
		log.info ("pwd: "+ password);
		log.info ("id: "+ userID);

		
		if (!User.Signin(userID, password)){
			resp.setContentType("text/html");
	        PrintWriter out = resp.getWriter();
	        out.println("<html>");
	        out.println("<head><title>Fail to Login!</title></head>");
	        out.println("<body>");
	        out.println("<h1>Login Failure</h1>");
	        out.println("Please try again!<br>");
	        out.println("<a HREF='javascript:history.back()'>Back</a>");
	        out.println("</body></html>");
		}else{
			//get type
			String type= User.getUserType(userID);
			
			//http session
			HttpSession session = req.getSession();
			session.setAttribute("id",userID);
			session.setAttribute("type", type);
			session.setMaxInactiveInterval(3600); // inactive for 1 hour
			
			// check user type
			if (type.equals("Seller")){
				forwardTo ="/seller.jsp";
			}else{
				forwardTo="/buyer.jsp";	
			}
			// redirect to user page
//			ServletContext sc = getServletContext();
//			RequestDispatcher rd = sc.getRequestDispatcher(forwardTo);
//			rd.forward(req, resp);
			resp.sendRedirect(forwardTo);
		}		
	}	
	
}
